package com.Drools.CIPS.ruler;

import com.Drools.CIPS.bean.DroolsReturn;
import com.prowidesoftware.swift.model.SwiftMessage;
import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;

@Service
public class Xlsx_MTRuler {

    /**
     *
     * @param pathXlsx 决策表的物理位置
     * @param sw 需要校验的报文
     * @return
     */
    public DroolsReturn XlsxRuler(String pathXlsx, SwiftMessage sw){
//        String pathXlsx = "src/main/resources/rule_xlsx/drools.xlsx";//指定决策表xls文件的磁盘路径
        File file = new File(pathXlsx);//读取文件
        InputStream is = null;
        try {
            is = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        SpreadsheetCompiler compiler = new SpreadsheetCompiler();
        String drl = compiler.compile(is, InputType.XLS);//xlsx文件转成drl字符串
        System.out.println("------------------------------------");
        System.out.println(drl);//输出查看字符串样子
        System.out.println("------------------------------------");

        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(drl, ResourceType.DRL);//读取drl的规则
        KieSession kieSession = kieHelper.build().newKieSession();

        DroolsReturn d = new DroolsReturn();//自定义的全局常量
        kieSession.setGlobal("retu",d);//放入全局变量
        kieSession.insert(sw);//放入数据
        int i = kieSession.fireAllRules(1);//校验   1表示只要触发一次规则就退出
        System.out.println(i);//输出命中几条规则
        kieSession.dispose();//关闭规则
        return d;
    }
}
